package com.redisdemo.controller;

import com.redisdemo.job.CommentJob;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * <h3>redisDemo</h3>
 * <p>定时任务控制类</p>
 *
 * @author gdw
 * @since 2024-06-26 14:34:55
 */
@RestController
@RequestMapping("/api/schedule")
public class ScheduleController {
    @Autowired
    private Scheduler scheduler;

    /**
     * 添加定时任务
     * @param jobName
     * @param jobGroup
     * @param triggerName
     * @param triggerGroup
     * @param cronExpression
     * @param param1
     * @param param2
     * @param isTrue
     * @return
     */
    @PostMapping("/create")
    public String createSchedule(
            @RequestParam String jobName,
            @RequestParam String jobGroup,
            @RequestParam String triggerName,
            @RequestParam String triggerGroup,
            @RequestParam String cronExpression,
            @RequestParam String param1,
            @RequestParam String param2,
            @RequestParam Boolean isTrue) {
        try {
            JobDetail jobDetail = JobBuilder.newJob(CommentJob.class)
                    .withIdentity(jobName, jobGroup)
                    .usingJobData("param1", param1)
                    .usingJobData("param2", param2)
                    .storeDurably()
                    .build();

            Trigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(triggerName, triggerGroup)
                    .withSchedule(CronScheduleBuilder.cronSchedule(cronExpression))
                    .forJob(jobDetail)
                    .build();

            scheduler.scheduleJob(jobDetail, trigger);
            if (isTrue) {
                scheduler.start();
            }
            return "Job scheduled successfully!";
        } catch (SchedulerException e) {
            e.printStackTrace();
            return "Error scheduling job: " + e.getMessage();
        }
    }

    /**
     * 修改定时任务
     *
     * @param jobName
     * @param jobGroup
     * @param triggerName
     * @param triggerGroup
     * @param newCronExpression
     * @param param1
     * @param param2
     * @return
     */
    @PostMapping("/update")
    public String updateSchedule(@RequestParam String jobName,
                                 @RequestParam String jobGroup,
                                 @RequestParam String triggerName,
                                 @RequestParam String triggerGroup,
                                 @RequestParam String newCronExpression,
                                 @RequestParam(required = false) String param1,
                                 @RequestParam(required = false) String param2,
                                 @RequestParam(required = false) Boolean isTrue) {
        try {
            // 获取现有的触发器
            TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroup);
            CronTrigger oldTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);

            if (oldTrigger == null) {
                return "Trigger not found";
            }
            // 判断是停止任务还是启用任务
            if (!isTrue) {
                scheduler.pauseTrigger(triggerKey);
                return "Job paused successfully!";
            } else {
                scheduler.resumeTrigger(triggerKey);
            }

            // 更新JobDetail的参数（如果提供）
            JobKey jobKey = new JobKey(jobName, jobGroup);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail != null && (param1 != null || param2 != null)) {
                JobDataMap jobDataMap = jobDetail.getJobDataMap();
                if (param1 != null) {
                    jobDataMap.put("param1", param1);
                }
                if (param2 != null) {
                    jobDataMap.put("param2", param2);
                }
                jobDetail = jobDetail.getJobBuilder().usingJobData(jobDataMap).storeDurably().build();
                scheduler.addJob(jobDetail, true);  // true to update existing job
            }

            // 创建新的触发器，使用新的Cron表达式
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(newCronExpression);

            TriggerBuilder<CronTrigger> triggerBuilder = oldTrigger.getTriggerBuilder();
            CronTrigger newTrigger = triggerBuilder
                    .withSchedule(scheduleBuilder)
                    .build();

            // 重置触发器
            scheduler.rescheduleJob(triggerKey, newTrigger);
            return "Schedule updated successfully!";
        } catch (SchedulerException e) {
            e.printStackTrace();
            return "Error updating schedule: " + e.getMessage();
        }
    }

    /**
     * 删除定时任务
     * @param jobName
     * @param jobGroup
     * @param triggerName
     * @param triggerGroup
     * @return
     * @throws SchedulerException
     */
    @PostMapping("/delete")
    public String deleteSchedule(@RequestParam String jobName,
                                 @RequestParam String jobGroup,
                                 @RequestParam String triggerName,
                                 @RequestParam String triggerGroup) throws SchedulerException {
        // 获取现有的触发器
        TriggerKey triggerKey = new TriggerKey(triggerName, triggerGroup);
        CronTrigger oldTrigger = (CronTrigger) scheduler.getTrigger(triggerKey);
        if (oldTrigger == null) {
            return "Trigger not found";
        }
        scheduler.unscheduleJob(triggerKey);
        JobKey jobKey = new JobKey(jobName, jobGroup);
        scheduler.deleteJob(jobKey);
        return "Job unscheduled successfully!";
    }

}
